import 'dart:convert';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hms_scan_kit/flutter_hms_scan_kit.dart';
import 'package:flutter_hms_scan_kit/scan_result.dart';
import 'package:get/get.dart';
import 'package:hygf/config/GlobalConfig.dart';
import 'package:keyboard_utils_fork/keyboard_listener.dart' as key_listener;
import 'package:keyboard_utils_fork/keyboard_utils.dart';

import 'package:package_info/package_info.dart';

import '../../../util/HDNavigator.dart';
import '../../../util/LoadingUtils.dart';
import 'state.dart';

class ScanPageLogic extends GetxController {
  final ScanPageState state = ScanPageState();
  

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void onReady() {
    super.onReady();
  }

  void closePage() {;
    LoadingUtils.dismiss();
    String codeString = state.dataList.join(",");
    HDNavigator.close(result: codeString);
  }

  Future<void> scan() async {
    if(!state.isReadOnly){
      ScanResult? scanResult = await FlutterHmsScanKit.startScan();
      if(scanResult?.value != null){
        LoadingUtils.showToast("识别条形码成功");
        print("条形码或二维码为: ${scanResult?.scanType},值：${scanResult?.value}" );
        if((scanResult?.value??"").contains("\n")){
          List<String> parts = (scanResult?.value??"").split(RegExp(r'[\n\s]+'));
          for (String part in parts) {
            if(part.isNotEmpty){
              state.dataList.add(part);
            }
          }
        }else{
          state.dataList.add(scanResult?.value);
        }
      }
      update();
    }
  }

  void removeItem(index) {
    if(!state.isReadOnly) {
      state.dataList.removeAt(index);
      update();
    }
  }


  
}
